package com.example.myhotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myhotel.entity.Book;
import com.example.myhotel.mapper.BookMapper;
import com.example.myhotel.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>implements BookService {
    @Autowired
    private BookService bookService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public boolean addBook(LocalDateTime time, String userId,String roomId){
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Book::getCustomerId,userId);
        List<Book> list = bookService.list(wrapper);
        Book book = new Book();
        if (list.size() == 0){
            book.setBookTime(time);
            book.setState(0);
            book.setCustomerId(userId);
            book.setRoomId(roomId);
            bookService.save(book);
            return true;
        }
        int count = chek(list,0);
        if (count == 0){
            book.setBookTime(time);
            book.setState(0);
            book.setCustomerId(userId);
            book.setRoomId(roomId);
            bookService.save(book);
            return true;
        }
        return false;
    }
    //判断用户是否已预定，或房间是否已被预定
    public int chek(List<Book> list,int number){
        int count = 0;
        for (Book book1 : list){
            if (book1.getState() ==number){//是否有预定的
                count++;
                break;
            }
        }
        return count;
    }

    @Override
    //判断是否有预定
    public boolean chekBook(String userId,String roomId) {
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId !=null,Book::getCustomerId,userId);
        wrapper.eq(roomId !=null,Book::getRoomId,roomId);
        List<Book> list = bookService.list(wrapper);
        int count = chek(list,0);
        if (count == 0){
            return true;//用户没有预定或房间没有被预定
        }
        return false;//用户有预定
    }
//根据userId或roomId删除预定信息
    @Override
    public void deleteBook(String userId, String roomId) {
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null,Book::getCustomerId,userId);
        wrapper.eq(roomId != null,Book::getRoomId,roomId);
        bookService.remove(wrapper);
    }

}
